﻿using amuudp.package;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace amuudp.sender
{
    public abstract class Sender
    {
        private IPEndPoint iPEndPoint;
        private UdpClient UdpClient = null;
        protected byte[] data;

        public int PackageId { get; private set; }

        private int index = 0;
        private int fragmentIndex = 0;

        public Sender(IPEndPoint iPEndPoint, byte[] data)
        {
            this.iPEndPoint = iPEndPoint;
            PackageId = new Random().Next();
            this.data = data;
        }

        public bool SendNext()
        {
            int size = data.Length;

            if (index >= size)
            {
                Close();
                return false;
            }

            if(UdpClient == null)
            {
                UdpClient = new UdpClient();
            }

            byte[] temp = UdpCommon.ByteCopy(data, index, size - index < UdpCommon.DataMaxLength ? size - index : UdpCommon.DataMaxLength);
            byte[] bytes = Fragment.CreateFragmentBytes(PackageId, size, fragmentIndex, temp);
            UdpClient.Send(bytes, bytes.Length, iPEndPoint);
            fragmentIndex++;
            index += UdpCommon.DataMaxLength;

            return true;
        }

        public void Send()
        {
            while (SendNext())
            {

            }
        }

        public void Close()
        {
            UdpClient.Close();
        }
    }

}
